<template>
  <absolute-container class="absolute-container p-[20px]">
    <div class="box-card page-main relative flex h-full flex-row rounded-[4px]">
      <MyDragResize ref="myDragResize" class="asideTreeBox main-shadow">
        <el-card
          shadow="never"
          class="h-full"
          :class="[isTreeShow ? 'mr-[16px] w-full overflow-y-auto' : 'w-[0px] border-none']"
        >
          <div class="p-[16px]">
            <el-input
              v-model="filterText"
              class="h-[32px] text-[14px]"
              size="small"
              placeholder="输入关键字进行过滤"
              clearable
              suffix-icon="el-icon-search"
            />
          </div>
          <el-tree
            ref="treeRef"
            :props="treeProps"
            :load="loadNode"
            lazy
            node-key="id"
            class="common-tree-aside is-current h-full"
            highlight-current
            @node-click="handleNodeClick"
          >
            <div slot-scope="{ node, data }" class="el-tree-node__label">
              <div class="c-t-label">
                <div v-popper="{ content: node.label }" class="ellipsis">{{ node.label }}</div>
              </div>
            </div>
          </el-tree>
        </el-card>

        <button
          class="shrinkBtn duration-700"
          :class="[isTreeShow ? 'right-[-12px]' : 'left right-[0px]']"
          @click="changeTreeShow"
        ></button>
      </MyDragResize>
      <el-card
        shadow="never"
        class="main-shadow flex flex-1 flex-col"
        :class="[isTreeShow ? 'ml-[20px]' : 'ml-[0px]']"
        :body-style="{ display: 'flex', 'flex-direction': 'column', height: '100%' }"
      >
        <div slot="header">
          <QueryForm
            ref="refQueryForm"
            :getDataList="getDataList"
            :multipleSelection="multipleSelection"
            :parentId="parentId"
            :nodeId="nodeId"
            @addDetailDrawer="addDetailDrawer"
            @addRolePermissions="addRolePermissions"
          ></QueryForm>
        </div>
        <div class="flex h-[calc(100%-0px)] flex-col px-[16px]">
          <el-table height="100%" :data="dataList" row-key="id" @selection-change="handleSelectionChange">
            <el-table-column reserve-selection type="selection" width="40" center></el-table-column>
            <el-table-column type="index" label="序号" width="60" :index="columnIndex" />
            <el-table-column
              :prop="PROPS.userAccount"
              :label="LABELS.userAccount"
              min-width="150"
              show-overflow-tooltip
            />
            <el-table-column :prop="PROPS.userName" :label="LABELS.userName" min-width="150" />
            <el-table-column :prop="PROPS.gender" :label="LABELS.gender" min-width="150">
              <template #default="{ row, $index }">
                <div class="flex items-center justify-start">
                  {{ $store.state.data.KV_MAP[OPTION_KEYS.gender][row[PROPS.gender]] }}
                </div>
              </template>
            </el-table-column>
            <el-table-column :prop="PROPS.phoneNumber" :label="LABELS.phoneNumber" min-width="150" />
            <el-table-column :prop="PROPS.title" :label="LABELS.title" min-width="150" />
            <el-table-column :prop="PROPS.role" :label="LABELS.role" min-width="600">
              <template #default="{ row, $index }">
                <div v-if="row[PROPS.role]" class="flex items-center overflow-x-auto px-1">
                  <!--                  <t-button v-for="(item, index) in row[PROPS.role].split(',')" :key="index" type="primary">{{ -->
                  <!--                    item -->
                  <!--                  }}</t-button> -->
                  <span>{{ row.roleString }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column :prop="PROPS.accountStatus" :label="LABELS.accountStatus" min-width="150">
              <template #default="{ row, $index }">
                <div
                  v-if="$store.state.data.KV_MAP[OPTION_KEYS.accountStatus][row[PROPS.accountStatus]]"
                  class="flex items-center"
                >
                  <div
                    class="mr-[8px] h-[6px] w-[6px] flex-shrink-0"
                    style="border-radius: 50%"
                    :class="[
                      $store.state.data.KV_MAP[OPTION_KEYS.accountStatus][row[PROPS.accountStatus]] == '正常'
                        ? 'bg-[#1D7FF2]'
                        : 'bg-[#CCCCCC]',
                    ]"
                  ></div>
                  {{ $store.state.data.KV_MAP[OPTION_KEYS.accountStatus][row[PROPS.accountStatus]] }}
                </div>
              </template>
            </el-table-column>
            <el-table-column class-name="!px-[0px]" label="操作" align="left" width="140" fixed="right">
              <template #default="{ row }">
                <div class="space-x-[12px]">
                  <span class="cursor-pointer text-[#1D7FF2]" @click="onDetail(row)">详情</span>
                  <span class="cursor-pointer text-[#1D7FF2]" @click="onEdit(row)">编辑</span>
                  <el-dropdown @command="handleCommand">
                    <span class="el-dropdown-link text-[#1D7FF2]">更多</span>
                    <el-dropdown-menu slot="dropdown" class="table-operates-dropdown">
                      <el-dropdown-item
                        v-if="!row.is_internal"
                        :command="{ type: 'del', value: row.id, username: row.username }"
                        class="color-danger"
                        >删除用户</el-dropdown-item
                      >
                      <el-dropdown-item :command="{ type: 'reset', value: row.id, username: row.username }"
                        >重置密码</el-dropdown-item
                      >
                      <el-dropdown-item
                        v-if="row.status == 'ENABLED'"
                        :command="{ type: 'free', value: row.id, username: row.username }"
                        >冻结账号</el-dropdown-item
                      >
                      <el-dropdown-item v-else :command="{ type: 'cancelFree', value: row.id, username: row.username }"
                        >解除冻结</el-dropdown-item
                      >
                      <el-dropdown-item
                        v-if="!row.is_internal"
                        :command="{ type: 'role', value: row.id, username: row.username }"
                        >分配权限</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
            <template slot="empty">
              <t-empty-data />
            </template>
          </el-table>
          <div class="addShadow relative -left-[16px] -top-[1px] z-50 w-[calc(100%+32px)]">
            <el-pagination
              :current-page="pagination.page"
              :total="pagination.total"
              :page-size="pagination.size"
              :page-sizes="pagination.sizes"
              :layout="pagination.layout"
              :hide-on-single-page="false"
              background
              @size-change="onSizeChange"
              @current-change="onCurrentChange"
            />
          </div>
        </div>
        <DetailDrawer :id="id" v-model="drawerVisible" :departId="nodeId" @onSubmit="onSubmit" />
        <DetailDrawerList :id="id" v-model="drawerVisibleList" />
        <AssignPermissions
          :id="id"
          v-model="drawerVisibleAssign"
          :nodeId="nodeId"
          :parentId="parentId"
          :username="username"
          :multipleSelection="multipleSelection"
          @onSubmitRole="onSubmitRole"
        ></AssignPermissions>
        <RolePermissions
          :id="id"
          v-model="drawerRoleVisibleAssign"
          :multipleSelection="multipleSelection"
          :nodeId="nodeId"
          :parentId="parentId"
          @onSubmitRole="onSubmitRole"
        ></RolePermissions>
      </el-card>
    </div>
  </absolute-container>
</template>

<script>
import config from "./config";
import QueryForm from "./components/QueryForm.vue";
import DetailDrawer from "./components/DetailDrawer.vue";
import DetailDrawerList from "./components/DetailDrawerList.vue";
import AssignPermissions from "./components/AssignPermissions.vue";
import RolePermissions from "./components/RolePermissions.vue";
import { systemDepartmentGetChildrenNodes } from "@/api/department";
import { systemUserAdd, systemUserList, systemUserUpdate } from "@/api/user";
import tableMixin from "@/mixin/table";
import paginationMixin from "@/mixin/pagination";

export default {
  name: "TenantUserMgmt",
  components: { DetailDrawer, QueryForm, DetailDrawerList, AssignPermissions, RolePermissions },
  mixins: [paginationMixin, tableMixin],
  data() {
    return {
      isTreeShow: true,
      multipleSelection: [],
      ...config,
      id: 1,
      nodeId: null,
      parentId: null, //父节点id
      username: "", //父节点id
      dataList: [],
      drawerVisible: false,
      drawerVisibleList: false,
      drawerVisibleAssign: false,
      drawerRoleVisibleAssign: false,
      treeProps: { label: "name", isLeaf: "childCount" },
      filterText: "",
    };
  },
  computed: {},
  watch: {
    filterText: {
      immediate: true,
      handler(newValue) {
        this.$refs.treeRef?.filter(newValue);
      },
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getDataList();
    },
    changeTreeShow() {
      this.isTreeShow = !this.isTreeShow;
      this.$refs.myDragResize.changWidth(this.isTreeShow);
    },
    getDataList(param) {
      return new Promise((resolve) => {
        const params = { ...this.getParams(param), departId: this.nodeId };
        systemUserList(params).then((res) => {
          this.dataList = res.content?.map((m) => ({ ...m, roleString: m.role.replaceAll(",", " | ") }));
          this.pagination.total = res.totalElements;
          resolve();
        });
      });
    },
    async loadNode(node, resolve) {
      if (node.level === 0) {
        const data = await systemDepartmentGetChildrenNodes({ parentId: 0, showDisabled: false });
        //默认选中第一个id
        data.map((item) => {
          item.childCount = item.isHaveChildNote ? false : true;
        });

        resolve(data);
        // this.$nextTick(() => {
        //   document.querySelector(".is-current").firstChild.click();
        // });
      } else {
        const dataNext = await systemDepartmentGetChildrenNodes({ parentId: node.data.id, showDisabled: false });
        // const data = await systemDepartmentGetChildrenUsers({ id: node.data.id });
        dataNext.map((item) => {
          item.childCount = item.isHaveChildNote ? false : true;
        });

        // if (data && data.length) {
        //   const dataNextUser = data.map((item) => {
        //     item.name = item.username;
        //     item.childCount = true;
        //     return item;
        //   });
        //   resolve(dataNextUser);
        // } else {
        resolve(dataNext);
        // }
      }
    },
    handleCommand(command) {
      const { type, value, username } = command;
      if (type == "del") {
        //删除用户
        this.$refs.refQueryForm.deletTenantUsers({
          list: [username],
          departId: this.parentId ? this.parentId : this.nodeId,
        });
      } else if (type == "reset") {
        //重置密码
        this.$refs.refQueryForm.passwordResetTenantUsers({
          list: [username],
          departId: this.parentId ? this.parentId : this.nodeId,
        });
      } else if (type == "free") {
        //冻结账号
        this.$refs.refQueryForm.updateBatchTenantUsers({
          list: [username],
          departId: this.parentId ? this.parentId : this.nodeId,
        });
      } else if (type == "cancelFree") {
        //解除账号
        this.$refs.refQueryForm.cancaelUpdateBatchTenantUsers({
          list: [username],
          departId: this.parentId ? this.parentId : this.nodeId,
        });
      } else if (type == "role") {
        //分配权限
        this.drawerVisibleAssign = true;
        this.id = value;
        this.username = username;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleNodeClick(node) {
      this.parentId = node.parentId;
      this.nodeId = node.id;
      this.getDataList(node.id);
    },
    addDetailDrawer() {
      this.id = 0; //false代表新增
      this.drawerVisible = true;
    },
    addRolePermissions(row) {
      this.drawerRoleVisibleAssign = true;
    },
    onDetail(row) {
      this.id = row.id;
      this.drawerVisibleList = true;
    },
    onAssign(row) {
      this.id = row.id;
      this.drawerVisibleAssign = true;
    },
    onEdit(row) {
      this.id = row.id;
      this.drawerVisible = true;
    },
    async onSubmit(value) {
      if (this.id) {
        //详情
        await systemUserUpdate(value);
      } else {
        //新增
        const params = {
          ...value,
        };
        await systemUserAdd(params);
      }
      this.onFinsh(this.nodeId);
    },
    onSubmitRole() {
      this.onFinsh();
    },
    onFinsh(value) {
      //value有值代表需要重置分页参数
      this.$message.success({
        message: "操作成功",
      });
      this.getDataList(value);
      this.drawerVisible = false;
      this.drawerVisibleAssign = false;
      this.drawerRoleVisibleAssign = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.addShadow {
  display: inline-flex;
  justify-content: flex-end;
  height: 68px;
  padding: 16px;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 -1px 4px 0 rgb(0 0 0 / 0.08);
}

:deep() {
  .el-table--fit {
    height: calc(100% - 40px) !important;
  }
}

::v-deep .is-leaf + .el-tree-node__label {
  padding-left: 4px;
}

::v-deep .el-tree-node__label {
  flex: 1;
  padding-right: 32px;
  overflow: hidden;
  text-overflow: ellipsis;
}

::v-deep .el-card__header {
  padding: 16px 16px 0;
  border-bottom: none;
}

::v-deep .el-card__body {
  height: 71.54%;
  padding: 0;
  overflow: auto;
}

.table-operates-dropdown {
  .el-dropdown-menu__item {
    height: 32px;
    padding: 0 8px !important;
    font-size: 14px;
    line-height: 32px !important;
  }
}
</style>
